package com.web.homework;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.web.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

@WebServlet("/work4")
public class work4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码
        request.setCharacterEncoding("UTF-8");
        // 设置响应内容类型和编码
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取学生ID
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            response.getWriter().println("ID参数不能为空");
            return;
        }
        int id = Integer.parseInt(idStr);

        // 搜索学生信息
        String student = searchStudentById(id);

        // 打印学生信息到控制台
        if (student != null) {
            System.out.println(student);
            response.getWriter().println("学生信息: " + student);
        } else {
            System.out.println("未找到学生信息");
            response.getWriter().println("未找到学生信息");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码
        request.setCharacterEncoding("UTF-8");
        // 设置响应内容类型和编码
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取学生姓名
        String name = request.getParameter("name");
        if (name == null || name.isEmpty()) {
            response.getWriter().println("姓名参数不能为空");
            return;
        }

        // 插入学生信息
        boolean success = insertStudent(name);

        // 打印结果到控制台
        if (success) {
            System.out.println("学生信息插入成功");
            response.getWriter().println("学生信息插入成功");
        } else {
            System.out.println("学生信息插入失败");
            response.getWriter().println("学生信息插入失败");
        }
    }

    // 通过ID搜索学生信息的方法
    private String searchStudentById(int id) {
        String studentName = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        DataSource dataSource = null;

        Properties properties = new Properties();
        try {
            // 读配置文件
            properties.load(DataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            // 初始化数据源
            dataSource = DruidDataSourceFactory.createDataSource(properties);

            // 获取连接
            connection = dataSource.getConnection();
            // 创建预编译语句
            String sql = "SELECT name FROM student WHERE id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, id);
            // 执行查询
            resultSet = preparedStatement.executeQuery();

            // 处理结果集
            if (resultSet.next()) {
                studentName = resultSet.getString("name");
            }
        } catch (IOException | SQLException e) {
            throw new RuntimeException("初始化数据源失败: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            try {
                if (resultSet != null) resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (preparedStatement != null) preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return studentName;
    }

    // 插入学生信息的方法
    private boolean insertStudent(String name) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        DataSource dataSource = null;

        Properties properties = new Properties();
        try {
            // 读配置文件
            properties.load(DataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            // 初始化数据源
            dataSource = DruidDataSourceFactory.createDataSource(properties);

            // 获取连接
            connection = dataSource.getConnection();
            // 创建预编译语句
            String sql = "INSERT INTO student (name) VALUES (?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, name);
            // 执行插入
            int affectedRows = preparedStatement.executeUpdate();

            // 返回插入是否成功
            return affectedRows > 0;
        } catch (IOException | SQLException e) {
            throw new RuntimeException("初始化数据源失败: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            try {
                if (preparedStatement != null) preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}